<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller {

    // num of records per page
    private $limit = 10;

    function __construct()
    {
        parent::__construct();

        // load library
        $this->load->library(array('table','form_validation'));

        // load helper
        $this->load->helper('url');

        // load model
        $this->load->model('admin/User_model','',TRUE);
        $this->is_logged_in();
        $this->isTeacher();
        $this->isAdmin();
    }
    function is_logged_in()
    {
        $is_logged_in = $this->session->userdata('logged_in');
        if(!isset($is_logged_in) || $is_logged_in != true)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    function isAdmin(){
        $isAdmin = $this->session->userdata('isAdmin');
        if($isAdmin == '' || $isAdmin != 'isAdmin')
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    function isTeacher(){
        $isTeacher = $this->session->userdata('isTeacher');
        if($isTeacher == '' || $isTeacher != 'isTeacher')
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    function index($offset = 0)
    {
        // offset
        if($this->isAdmin()){
        $uri_segment = 3;
        $offset = $this->uri->segment($uri_segment);

        // load data
        $users = $this->User_model->get_paged_list($this->limit, $offset)->result();

        // generate pagination
        $this->load->library('pagination');
        $config['base_url'] = site_url('admin/user/index/');
        $config['total_rows'] = $this->User_model->count_all();
        $config['per_page'] = $this->limit;
        $config['uri_segment'] = $uri_segment;
        $this->pagination->initialize($config);
        $data['pagination'] = $this->pagination->create_links();

        // generate table data
        $this->load->library('table');
        $this->table->set_empty("&nbsp;");
        $this->table->set_heading('STT', 'Id_User', 'Full Name', 'User','Passowrd','State','Permission','Tên','Số điện thoại','email','Địa chỉ', 'Actions');
        $i = 0 + $offset;
        foreach ($users as $user)
        {
            $this->table->add_row(++$i, $user->id_user,$user->fullname,$user->user,$user->password,$user->state,$user->permission,$user->ten,$user->sdt,$user->email,$user->diachi,
                anchor('admin/user/view/'.$user->id_user,'view',array('class'=>'view')).' '.
                    anchor('admin/user/update/'.$user->id_user,'update',array('class'=>'update')).' '.
                    anchor('admin/user/delete/'.$user->id_user,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure want to delete this account ?')"))
            );
        }
        $data['table'] = $this->table->generate();

        // load view
        $this->load->view('admin/users/userList', $data);
        }else{
            redirect('admin/khoahoc');
        }
    }

    function add()
    {
        // set empty default form field values
        $this->_set_fields();
        // set validation properties
        $this->_set_rules();

        // set common properties
        $data['title'] = 'Add new Acount';
        $data['message'] = '';
        $data['action'] = site_url('admin/user/addUser');
        $data['link_back'] = anchor('admin/user/index/','Back to list of Users',array('class'=>'back'));

        // load view
        $this->load->view('admin/users/userEdit', $data);
    }

    function addUser()
    {
        // set common properties
        $data['title'] = 'Add new account';
        $data['action'] = site_url('admin/user/addUser');
        $data['link_back'] = anchor('admin/user/index/','Back to list of users',array('class'=>'back'));

        // set empty default form field values
        $this->_set_fields();
        // set validation properties
        $this->_set_rules();

        // run validation
        if ($this->form_validation->run() == FALSE)
        {
            $data['message'] = '';
        }
        else
        {
            // save data
            $user = array('fullname' => $this->input->post('fullname'),
                'user' => $this->input->post('user'),
                'password' => sha1($this->input->post('password')),
                'state'=>$this->input->post('state'),
                'permission'=>$this->input->post('permission'),
                'ten'=>$this->input->post('ten'),
                'sdt'=>$this->input->post('sdt'),
                'email'=>$this->input->post('email'),
                'diachi'=>$this->input->post('diachi')
            );
            //$id = $this->User_model->save($user);
            $id_user =$this->User_model->save($user);

            // set user message
            $data['message'] = '<div class="success">add new account success</div>';
        }

        // load view
        $this->load->view('admin/users/userEdit', $data);
    }

    function view($id_user)
    {
        // set common properties
        $data['title'] = 'Account Details';
        $data['link_back'] = anchor('admin/user/index/','Back to list of Users',array('class'=>'back'));

        // get person details
        $data['user'] = $this->User_model->get_by_id($id_user)->row();

        // load view
        $this->load->view('admin/users/userView', $data);
    }

    function update($id_user)
    {
        // set validation properties
        $this->_set_rules();

        // prefill form values
        $user = $this->User_model->get_by_id($id_user)->row();
        $this->form_data->id_user = $id_user;
        $this->form_data->fullname = $user->fullname;
        $this->form_data->user = $user->user;
        $this->form_data->password= $user->password;
        $this->form_data->state= $user->state;
        $this->form_data->permission= $user->permission;
        $this->form_data->ten= $user->ten;
        $this->form_data->sdt= $user->sdt;
        $this->form_data->email= $user->email;
        $this->form_data->diachi= $user->diachi;


        // set common properties
        $data['title'] = 'Update Account';
        $data['message'] = '';
        $data['action'] = site_url('admin/user/updateAccount');
        $data['link_back'] = anchor('admin/user/index/','Back to list of users',array('class'=>'back'));

        // load view
        $this->load->view('admin/users/userEdit', $data);
    }

    function updateAccount()
    {
        // set common properties
        $data['title'] = 'Update account';
        $data['action'] = site_url('admin/user/updateAccount');
        $data['link_back'] = anchor('admin/user/index/','Back to list of accounts',array('class'=>'back'));

        // set empty default form field values
        $this->_set_fields();
        // set validation properties
        $this->_set_rules();

        // run validation
        if ($this->form_validation->run() == FALSE)
        {
            $data['message'] = '';
        }
        else
        {
            // save data
            $id_user = $this->input->post('id_user');
            $user = array('fullname' => $this->input->post('fullname'),
                'user' => $this->input->post('user'),
                'password' => $this->input->post('password'),
                'state'=>$this->input->post('state'),
                'permission'=>$this->input->post('permission'),
                'ten'=>$this->input->post('ten'),
                'sdt'=>$this->input->post('sdt'),
                'email'=>$this->input->post('email'),
                'diachi'=>$this->input->post('diachi')
            );

            $this->User_model->update($id_user,$user);

            // set user message
            $data['message'] = '<div class="success">Update User success</div>';
        }

        // load view
        $this->load->view('admin/users/userEdit', $data);
    }

    function delete($id_user)
    {
        // delete person
        $this->User_model->delete($id_user);

        // redirect to person list page
        redirect('admin/user/index/','refresh');
    }

    // set empty default form field values
    function _set_fields()
    {
        $this->form_data->id_user = '';
        $this->form_data->fullname = '';
        $this->form_data->user = '';
        $this->form_data->password= '';
        $this->form_data->state= '';
        $this->form_data->permission= '';
        $this->form_data->ten= '';
        $this->form_data->sdt= '';
        $this->form_data->email= '';
        $this->form_data->diachi= '';
    }

    // validation rules
    function _set_rules()
    {
        $this->form_validation->set_rules('fullname', 'Fullname', 'trim|required');
        $this->form_validation->set_rules('user', 'user', 'trim|required');
        $this->form_validation->set_rules('password', 'password', 'trim|required');
        $this->form_validation->set_rules('sdt', 'sdt', 'trim|required');
        $this->form_validation->set_rules('ten', 'ten', 'trim|required');




        $this->form_validation->set_message('required', '* Vui lòng điền thông tin vào ');
        $this->form_validation->set_message('isset', '* required');
        $this->form_validation->set_message('valid_date', 'date format is not valid. dd-mm-yyyy');
        $this->form_validation->set_error_delimiters('<p class="error">', '</p>');
    }

    // date_validation callback
    function valid_date($str)
    {
        //match the format of the date
        if (preg_match ("/^([0-9]{2})-([0-9]{2})-([0-9]{4})$/", $str, $parts))
        {
            //check weather the date is valid of not
            if(checkdate($parts[2],$parts[1],$parts[3]))
                return true;
            else
                return false;
        }
        else
            return false;
    }
}
?>